package com.quan.server.helper.pay;

import com.mark.util.CommonUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.TreeMap;

/**
 * Created by 桑博 on 2016/12/26.
 */
public class WeChatSendRedPack {

    private static Logger logger = LoggerFactory.getLogger(WeChatSendRedPack.class);
    public static final String secret = "DzCXx7JUJvoLd8j6x7iKT6uLBLSuNvgo";

    public static final String openIdMark = "ooNnQwabwaLA5VMNCn5EhoNkT_Zw";

    public static final String mch_id = "1494078932";//商户号

    public static final String weixinMPAppId = "wx9777714c30356a16";

    public static void main(String[] args) {
        sendRedPackage(openIdMark, 100);
    }

//
//    public static void main(String[] args) throws Exception {
//
//        //具体参数查看具体实体类，实体类中的的参数参考微信的红包发放接口，这里你直接用map，进行设置参数也可以。。。
//        SendRedPack sendRedPack = new SendRedPack(
//            CommonUtil.createRandom32String(),//                "随机字符串不超过32位",
//            CommonUtil.createRandomString(28), //                "随机订单号，不超过28位",
//            "1494078932", //                "商户号",
//            "wx9777714c30356a16",//                "公众号appid",
//            "牛起蒙", //                "桑博",
//            "ooNnQwabwaLA5VMNCn5EhoNkT_Zw", // macmatilda               "填写接受人的openid",
//            100,//                100,
//            1,//                1,
//            "赚钱多多",//                "萌萌哒",
//            "127.0.0.1",//                "127.0.0.1",
//            "红包",//                "桑博红包",
//            "提现",//备注                "桑博",
//            "PRODUCT_5"//PRODUCT_5:渠道分润//                "PRODUCT_5"
//        );
//
//        //将实体类转换为url形式
//        String urlParamsByMap = Tool.getUrlParamsByMap(Tool.toMap(sendRedPack));
//        //拼接我们再前期准备好的API密钥，前期准备第5条
//        urlParamsByMap += "&key=" + secret;
//        //进行签名，需要说明的是，如果内容包含中文的话，要使用utf-8进行md5签名，不然会签名错误
//        String sign = Tool.parseStrToMd5L32(urlParamsByMap).toUpperCase();
//        sendRedPack.setSign(sign);
//        //微信要求按照参数名ASCII字典序排序，这里巧用treeMap进行字典排序
//        TreeMap treeMap = new TreeMap(Tool.toMap(sendRedPack));
//        //然后转换成xml格式
//        String soapRequestData = Tool.getSoapRequestData(treeMap);
//        //发起请求前准备
//        RequestBody body = RequestBody.create(MediaType.parse("text/xml;charset=UTF-8"), soapRequestData);
//        Request request = new Request.Builder()
//            .url("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack")
//            .post(body)
//            .build();
//        //为http请求设置证书
//        SSLSocketFactory socketFactory = getSSLContext().getSocketFactory();
////        X509TrustManager x509TrustManager = Platform.get().trustManager(socketFactory);
////        OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(socketFactory, x509TrustManager).build();
//        OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(socketFactory).build();
//
//        //得到输出内容
//        Response response = okHttpClient.newCall(request).execute();
//        String content = response.body().string();
//        System.out.println(content);
//    }

    public static void sendRedPackage(String openId, int money) {

        try {
//具体参数查看具体实体类，实体类中的的参数参考微信的红包发放接口，这里你直接用map，进行设置参数也可以。。。
            SendRedPack sendRedPack = new SendRedPack(
                CommonUtil.createRandom32String(),//                "随机字符串不超过32位",
                CommonUtil.createRandomString(28), //                "随机订单号，不超过28位",
                mch_id, //                "商户号",
                weixinMPAppId,//                "公众号appid",
                "牛起蒙", //                "桑博",
                openId, // macmatilda               "填写接受人的openid",
                money,//                100,
                1,//                1,
                "赚钱多多",//                "萌萌哒",
                "127.0.0.1",//                "127.0.0.1",
                "红包",//                "桑博红包",
                "提现",//备注                "桑博",
                "PRODUCT_5"//PRODUCT_5:渠道分润//                "PRODUCT_5"
            );

            //将实体类转换为url形式
            String urlParamsByMap = Tool.getUrlParamsByMap(Tool.toMap(sendRedPack));
            //拼接我们再前期准备好的API密钥，前期准备第5条
            urlParamsByMap += "&key=" + secret;
            //进行签名，需要说明的是，如果内容包含中文的话，要使用utf-8进行md5签名，不然会签名错误
            String sign = Tool.parseStrToMd5L32(urlParamsByMap).toUpperCase();
            sendRedPack.setSign(sign);
            //微信要求按照参数名ASCII字典序排序，这里巧用treeMap进行字典排序
            TreeMap treeMap = new TreeMap(Tool.toMap(sendRedPack));
            //然后转换成xml格式
            String soapRequestData = Tool.getSoapRequestData(treeMap);
            //发起请求前准备
            RequestBody body = RequestBody.create(MediaType.parse("text/xml;charset=UTF-8"), soapRequestData);
            Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack")
                .post(body)
                .build();
            //为http请求设置证书
            SSLSocketFactory socketFactory = getSSLContext().getSocketFactory();
            final X509TrustManager x509TrustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            };
            OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(socketFactory, x509TrustManager).build();
//            OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(socketFactory).build();

            //得到输出内容
            Response response = okHttpClient.newCall(request).execute();
            String content = response.body().string();
            System.out.println(content);
            logger.error(content);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

//     <xml>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<return_msg><![CDATA[发放成功]]></return_msg>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<err_code><![CDATA[SUCCESS]]></err_code>
//<err_code_des><![CDATA[发放成功]]></err_code_des>
//<mch_billno><![CDATA[HwelJJjMk74EVltZoOCCBCnrdO0B]]></mch_billno>
//<mch_id><![CDATA[1494078932]]></mch_id>
//<wxappid><![CDATA[wx9777714c30356a16]]></wxappid>
//<re_openid><![CDATA[ooNnQwabwaLA5VMNCn5EhoNkT_Zw]]></re_openid>
//<total_amount>100</total_amount>
//<send_listid><![CDATA[1000041701201803033000448629304]]></send_listid>
//</xml>

//
//    public static SSLContext getSSLContext() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
//        KeyStore keyStore = KeyStore.getInstance("PKCS12");
//        //证书位置自己定义
//        FileInputStream instream = new FileInputStream(new File("D:/soft/apiclient_cert.p12"));
//        try {
//            keyStore.load(instream, "填写证书密码，默认为商户号".toCharArray());
//        } finally {
//            instream.close();
//        }
//        SSLContext sslcontext = SSLContexts.custom()
//                .loadKeyMaterial(keyStore, "填写证书密码，默认为商户号".toCharArray())
//                .build();
//        return sslcontext;
//    }

    public static SSLContext getSSLContext() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //证书位置自己定义
//        FileInputStream instream = new FileInputStream(new File("/Users/macmatilda/gitee/quan/quan.server/src/main/resources/cert/apiclient_cert.p12"));
        InputStream instream = null;
        try {
            instream = CommonUtil.readResource("./cert/apiclient_cert.p12");
            keyStore.load(instream, mch_id.toCharArray());
        } finally {
            if (instream != null) {
                instream.close();
                instream = null;
            }
        }
        SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keyStore, mch_id.toCharArray())
            .build();
        return sslcontext;
    }

//    /Users/macmatilda/gitee/quan/quan.server/src/main/resources/cert/apiclient_cert.p12
}